package com.cskaoyan.shiro;

import com.cskaoyan.mapper.AdminMapper;

import com.cskaoyan.typehandler.String2IntegerArr;
import lombok.SneakyThrows;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    AdminMapper adminMapper;


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //根据username获取数据库中对应的password
        MallToken token = (MallToken) authenticationToken;
        String username = token.getUsername();
        List<String> passwords = adminMapper.selectPasswordByName(username);

        String credential =  passwords.size() >= 1 ? passwords.get(0) : "";

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,credential,this.getName());
        return authenticationInfo;

    }

    @SneakyThrows
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //第一个参数 是我们存入的username
        String username = (String) principalCollection.getPrimaryPrincipal();

        //查询 该用户对应的角色信息 ---- 通过角色信息获得对应的权限信息
        String roleIdsString = adminMapper.selectRoleIdsByName(username);
        Integer[] roleIds = String2IntegerArr.toIntegerArray(roleIdsString);
        List<String> permissions = adminMapper.selectPermissionsByRoleIds(roleIds);

        //通过权限信息获取
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;

  }

}
